package com.link.base.base.saleactivity.controller;

import com.link.base.base.email.model.EmailInfo;
import com.link.base.base.email.service.EmailService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.service.BasicService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author wangdawei
 * @date 2018/6/10
 * 网络图片，音乐MP3等转成Base64码Controller
 */
@Controller
@RequestMapping("/link/fileConversion")
public class ImageConversionController extends BasicController<EmailInfo> {

    @Resource
    private EmailService emailService;

    @Override
    public BasicService<EmailInfo> getBasicService() throws Exception {
        return emailService;
    }

    /**
     * 将网络图片转成Base64码，此方法可以解决图片不支持下载问题
     * @author wangdawei
     * @param imgURL 例如：http://***.com/271025191524034.jpg
     * @return
     */
    @RequestMapping(value = "/imageToBase64")
    @ResponseBody
    public String imgBase64(@RequestParam String imgURL) throws Exception {
        ByteArrayOutputStream outPut = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        URL url = new URL(imgURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        try {
            // 创建URL
            // 创建链接
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);

            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                //连接失败/链接失效/图片不存在
                return "fail";
            }
            InputStream inStream = conn.getInputStream();
            int len = -1;
            while ((len = inStream.read(data)) != -1) {
                outPut.write(data, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            LCLogger.withException(e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String result = "data:image/png;base64," + encoder.encode(outPut.toByteArray());
        return result;
    }
}
